/**
 * https://leetcode.cn/problems/degree-of-an-array/
 */
function findShortestSubArray(nums: number[]): number {
  const map = new Map<number, number[]>();

  for (let i = 0; i < nums.length; i++) {
    const current = nums[i];
    const target = map.get(current);
    if (target) {
      target[0]++;
      target[2] = i;
    } else {
      map.set(current, [1, i, i]);
    }
  }

  let ans = 0;
  let maxLength = 0;
  for (let [, [count, left, right]] of map) {
    const currentLength = right - left + 1;
    if (count > maxLength) {
      ans = currentLength;
      maxLength = count;
    } else if (count === maxLength) {
      ans = Math.min(currentLength, ans);
    }
  }

  return ans;
}

function findShortestSubArrayV2(nums: number[]): number {
  const map = new Map<number, number[]>();

  let maxLength = 0;
  let targetNums: number[] = [];

  for (let i = 0; i < nums.length; i++) {
    const current = nums[i];
    let target = map.get(current);
    if (target !== undefined) {
      // 说明已经重复了
      target.push(i);
    } else {
      target = [i];
      map.set(current, target);
    }

    if (target.length > maxLength) {
      maxLength = target.length;
      targetNums = [current];
    } else if (target.length === maxLength) {
      targetNums.push(current);
    }
  }
  let ans = Number.MAX_SAFE_INTEGER;
  for (let num of targetNums) {
    const array = map.get(num)!;
    ans = Math.min(array[array.length - 1] - array[0] + 1, ans);
  }

  return ans;
}
